/*
 * Copyright (c) 2011 Jean-Marc Perronne
 * Ensisa, 12 rue des Freres Lumieres, F-68093 Mulhouse cedex
 * All rights reserved.
 *
 * The copyright of this software is owned by Werner Randelshofer. 
 * You may not use, copy or modify this software, except in  
 * accordance with the license agreement you entered into with  
 * Jean-Marc Perronne. For details see accompanying license terms. 
 */

package fr.uha.ensisa.jmp.drone.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.rmi.ConnectException;

import fr.uha.ensisa.jmp.drone.com.BadInterfaceException;
import fr.uha.ensisa.jmp.drone.com.ConfigConnection;
import fr.uha.ensisa.jmp.drone.configuration.Configurations;


public class ConfigHandler extends ChildDroneHandler<String[]>
{
	private ConfigConnection com;

	public ConfigHandler(DroneHandler drone) throws SocketException, UnknownHostException, BadInterfaceException
	{
		super(drone);
		this.com = new ConfigConnection();
	}

	@Override
	public void run()
	{
		try
		{
			BufferedReader reader = null;
			this.running();
			while(this.isActive() && this.drone.isActive())
			{
				try
				{
					if (!this.com.isConnected())
					{
						this.com.connect();
						reader = new BufferedReader(new InputStreamReader(this.com.getInputStream()));
					}				
					

					String line = reader.readLine();
					if (line == null)
					{
						//System.out.println ("pb---------------");
						break;
					}
					
					if(line != null)
					{
						String[] config = Configurations.parseAConfigLine(line);
						if (config != null) this.data().put(config);
						else System.err.println("config line malformed: " + line);
					}		
				
					Thread.yield();
				}
				catch (ConnectException e)
				{
					e.printStackTrace();
				}
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		finally
		{
			this.close();
			this.terminate();
			this.notRrunning();
		}
	}
	
	public void start()
	{
		super.start();
		new Thread(this).start();
	}
	
	@Override
	public void close()
	{
		try
		{
			this.com.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
	}
}
